/*
 * =====================================================================================
 *
 *       Filename:  filecaching.c
 *
 *    Description:  Implementation of functions and structures for file caching
 *
 *        Version:  1.0
 *        Created:  28/10/2010 15:32:41
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  François Hissel (), francois.hissel@developpement-durable.gouv.fr
 *        Company:  CETMEF
 *
 * =====================================================================================
 */

#include	<stdio.h>
#include	<stdlib.h>
#include	<string.h>
#include	"filecaching.h"

int cache_id=1;

FileList *create_file_list(long handle,const char *path,Folder *folder) {
	FileList *fl=malloc(sizeof(FileList));
	fl->file.handle=handle;
	if (path==0) fl->file.path=0; else {
		fl->file.path=malloc(strlen(path)+1);
		strcpy(fl->file.path,path);
	}
	fl->file.folder=folder;
	fl->file.id=cache_id;
	if (folder!=0 && handle!=0) {
		folder->file->id=cache_id++;
	}
	return fl;
}

void free_file_list(FileList *list) {
	FileList *fl=list;
	FileList *tmp;
	while (fl!=0) {
		tmp=fl->next;
		if (fl->file.handle!=0) close(fl->file.handle);
		free(fl->file.path);
		free(fl);
		fl=tmp;
	}
}

void get_local_file_name(int id,char *name) {
	sprintf(name,"%s/ngfs%i",P_tmpdir,id);
}

FileList *find_handle(FileList *list,long handle) {
	FileList *p=list;
	while (p!=0 && p->file.handle!=handle) p=p->next;
	return p;
}

FileList *find_name(FileList *list,const char *name) {
	FileList *p=list;
	while (p!=0 && (p->file.path==0 || strcmp(p->file.path,name)!=0)) p=p->next;
	return p;
}

int free_handle(FileList **list,FileList *pointer) {
	if (*list==0) return -1;
	FileList *p;
	if (*list==pointer) {	// The first element needs to be deleted
		p=*list;
		*list=p->next;
		p->next=0;
		free_file_list(p);
	} else {
		p=*list;
		while (p->next!=0 && p->next!=pointer) p=p->next;	// Go to the element just before the one to be deleted
		if (p->next==0) return -1;
		FileList *q=p->next;
		p->next=q->next;
		q->next=0;
		free_file_list(q);
	}
	return 0;
}

#ifdef TRACE
void print_file_list(FILE *file,FileList *list) {
	while (list!=0) {
		fprintf(file,"%p,%li,%s,%p\n",list,list->file.handle,list->file.path,list->file.folder);
		list=list->next;
	}
}
#endif
